package project.server.game;

import java.util.ArrayList;
import java.util.Iterator;

import project.server.handlers.Client;
import project.server.handlers.OutboundMessages;
import project.server.handlers.Sessions;
import project.server.util.Logger;
import project.shared.util.Config;

public class GameAssembler extends Thread {
	private Sessions sessions;
	private OutboundMessages outQueue;
	private ArrayList<Client> newGame = new ArrayList<Client>();
	private int gameId = 0;
	private Logger logger;
	private Config config;

	public GameAssembler(Sessions sessions, OutboundMessages out, Logger log, Config cfg){
		this.sessions = sessions;
		this.outQueue = out;
		this.logger = log;
		this.config = cfg;
		start();
	}
	
	public void run(){
		while(true){
			synchronized(sessions){
				Iterator<Client> it = sessions.iterator();
				while(it.hasNext()){
					Client cli = it.next();
					if(!cli.getInGame()){
						newGame.add(cli);
						cli.setInGame();
					}
					
					if(newGame.size() == 3){
						if(!checkAlive()){
							break;
						}
						newGame.clear();
						break;
					}
				}
			}
		}
	}
	
	public boolean checkAlive(){
		try{
			sleep(3000);
		}catch(InterruptedException e){
			logger.logError("GameAssembler - checkAlive() - sleep interrupted.");
		}
		
		boolean ok = true;
		Iterator<Client> itr = newGame.iterator();
		while(itr.hasNext()){
			Client cli = itr.next();
			if(!cli.isAlive()){
				itr.remove();
				ok = false;
			}
		}
		return ok;
	}
}
